import traceback
import os
from uuid import uuid4

from fastapi import FastAPI, Request
# from fastapi.responses import JSONResponse

from boot.router import root_router

from app.config import config
# from app.utils.tts_paddle import init as init_paddle
# from app.utils.tts_gpt_sovits import init as init_gpt_sovits
# from app.utils.logger import logger
# from app.utils.response import response
# from app.utils import state
# from app.models.http_exception import HttpException


def create_application() -> FastAPI:
    instance = FastAPI(
        title=config.server_name,
        debug=config.server_debug,
    )

    instance.include_router(root_router)
    # instance.add_exception_handler(HttpException, exception_handler)
    # register_event(instance)

    return instance


# def exception_handler(request: Request, e: HttpException):
#     return JSONResponse(
#         status_code=e.status_code,
#         content=response(e.status_code, e.data, e.message),
#     )


# def register_event(app):
#     @app.on_event("startup")
#     async def startup_event():
#         try:
#             script_path = os.path.abspath(__file__)
#             script_dir = os.path.dirname(os.path.dirname(script_path))
#
#             # init_paddle()
#             init_gpt_sovits(script_dir)
#             pass
#         except Exception as e:
#             traceback.print_exc()
#         finally:
#             state.init_task()
#             state.start_runing()
#             logger.info(f"{config.project_name} on running")
#
#     @app.middleware("http")
#     async def check_header(request: Request, call_next):
#         # 无task-id时 手动指定task-id
#         if not request.headers.get("x-task-id"):
#             request.state.task_id = str(uuid4())
#         else:
#             request.state.task_id = str(request.headers.get("x-task-id"))
#
#         # 回调地址
#         if not request.headers.get("x-callback-url"):
#             request.state.callback_url = ''
#         else:
#             request.state.callback_url = str(request.headers.get("x-callback-url"))
#
#         response = await call_next(request)
#         return response
#
#     @app.on_event("shutdown")
#     async def shutdown_event():
#         try:
#             state.stop_runing()
#             logger.info(f"{config.project_name} on shutdown")
#         except Exception as e:
#             traceback.print_exc()


app = create_application()
